---
import PageLayout from "@/layouts/Base";
import BlogPostPreview from "@/components/BlogPostPreview";
import Pagination from "@/components/Paginator";
import { getAllTags, sortMDByDate } from "src/util";
import type { Post, Page, MDXInstance } from "@/types";

export async function getStaticPaths({ paginate }) {
	const allPosts = await Astro.glob<Post>("./*.mdx");
	const allPostsByDate = sortMDByDate(allPosts);
	const allTags = getAllTags(allPosts);
	return paginate(allPostsByDate, { props: { allTags }, pageSize: 10 });
}

export interface Props {
	page: Page<MDXInstance<Post>>;
	allTags: string[];
}

const { page, allTags } = Astro.props as Props;

const meta = {
	title: "Posts",
	description: "A collection of posts by me for a starter Astro theme",
};

const paginationProps = {
	...(page.url.prev && {
		prevUrl: {
			url: page.url.prev,
			text: `← Previous Posts`,
		},
	}),
	...(page.url.next && {
		nextUrl: {
			url: page.url.next,
			text: `Next Posts →`,
		},
	}),
};
---

<PageLayout meta={meta}>
	<h1 class="mb-6 title">文章列表</h1>
	<div class="grid gap-y-16 sm:grid-cols-[3fr_1fr] sm:gap-x-8">
		<section aria-label="Blog post list">
			<ul class="text-left space-y-8">
				{
					page.data.map((p) => (
						<li class="flex flex-wrap items-center gap-x-2 [&_q]:w-full">
							<BlogPostPreview post={p} as="h2" withDesc />
						</li>
					))
				}
			</ul>
			<Pagination {...paginationProps} />
		</section>
		{
			allTags.length && (
				<aside>
					<h2 class="flex items-center mb-4 text-lg font-semibold">
						<svg
							aria-hidden="true"
							xmlns="http://www.w3.org/2000/svg"
							class="w-6 h-6"
							viewBox="0 0 24 24"
							stroke-width="1.5"
							stroke="currentColor"
							fill="none"
							stroke-linecap="round"
							stroke-linejoin="round"
						>
							<path stroke="none" d="M0 0h24v24H0z" fill="none" />
							<path d="M7.859 6h-2.834a2.025 2.025 0 0 0 -2.025 2.025v2.834c0 .537 .213 1.052 .593 1.432l6.116 6.116a2.025 2.025 0 0 0 2.864 0l2.834 -2.834a2.025 2.025 0 0 0 0 -2.864l-6.117 -6.116a2.025 2.025 0 0 0 -1.431 -.593z" />
							<path d="M17.573 18.407l2.834 -2.834a2.025 2.025 0 0 0 0 -2.864l-7.117 -7.116" />
							<path d="M6 9h-.01" />
						</svg>
						Tags
					</h2>
					<ul class="flex flex-wrap gap-2 text-bgColor">
						{allTags.map((tag) => (
							<li>
								<a
									class="flex items-center justify-center p-1 rounded-lg bg-accent"
									href={`/tags/${tag}`}
									aria-label={`View all posts with the tag: ${tag}`}
								>
									{tag}
								</a>
							</li>
						))}
					</ul>
					<span class="block mt-4 sm:text-right">
						<a
							class="sm:hover:text-accent"
							href="/tags"
							aria-label="View all blog categories"
						>
							View all →
						</a>
					</span>
				</aside>
			)
		}
	</div>
</PageLayout>
